package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.adapter.CompanySignOutAdapter;
import com.lishe.lishe.lishe.module.excitation.adapter.StringAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.company.CompanyInfo;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.lishe.widget.MListDialog;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.InfoArrayObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/12/25.
 * 离职/退出企业
 */

public class SignOutCompanyActivity extends BaseActivity implements View.OnClickListener {

    private Button callBack;
    private TextView rigthText;
    private TextView title;
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private CompanySignOutAdapter adapter;
    private List<CompanyInfo> companys = new ArrayList<>();
    private int type = 1;//类型： 1：离职，2：退出
    private String comID = null;

    private RelativeLayout empatyLayout;
    private ImageView empatyImage;
    private TextView empatyText;

    public static void jump(Activity activity) {
        Intent itent = new Intent(activity, SignOutCompanyActivity.class);
        activity.startActivity(itent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_out_company);
        adapter = new CompanySignOutAdapter(companys);
        initView();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        rigthText = findViewById(R.id.title_rigth_text1);
        rigthText.setVisibility(View.VISIBLE);
        title = findViewById(R.id.title_text_title);
        title.setText("退出企业");
        rigthText.setText("完成");

        refreshLayout = findViewById(R.id.refreshlayout);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        empatyLayout = findViewById(R.id.empty_layout);
        empatyImage = findViewById(R.id.empty_image);
        empatyText = findViewById(R.id.empty_text);
        setListenter();
    }

    private void setListenter() {
        callBack.setOnClickListener(this);
        rigthText.setOnClickListener(this);
        adapter.setOnItemClick(new CompanySignOutAdapter.OnItemtClick() {
            @Override
            public void onItemClick(int position, Object object) {
                comID = companys.get(position).getComId();
                createDialog(companys.get(position));
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getCompanyList();
            }
        });
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getCompanyList();
    }

    /**
     * 获取企业列表
     */
    private void getCompanyList() {
        ExcitationPresenter.getInstance().getUserComAll(Globals.getToken(), new DataResponseListener<InfoArrayObject>() {
            @Override
            public void onSuccess(InfoArrayObject dataResponse) {
                refreshLayout.finishRefresh();
                companys.clear();
                companys.addAll(dataResponse.getInfo());
                adapter.notifyDataSetChanged();
                if (companys.size() > 0) {
                    empatyLayout.setVisibility(View.GONE);
                } else {
                    empatyLayout.setVisibility(View.VISIBLE);
                    empatyText.setText("没有企业！");
                    AppManager.getAppManager().exitApp();
                    MainActivity0.jump(SignOutCompanyActivity.this, 0);
                }
            }

            @Override
            public void onFail(String failMessage) {
                refreshLayout.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.title_rigth_text1:
                finish();
                break;
        }
    }

    List<String> list = new ArrayList<>();

    private void createDialog(CompanyInfo companyInfo) {
        list.clear();
        if (companyInfo != null && companyInfo.getEmpStatus() != null) {
            if (companyInfo.getEmpStatus().equals("-1")) {//未确认
                list.add("这不是我的企业，退出");
            }else{
                list.add("我已从这家公司离职，退出");
                list.add("这不是我的企业，退出");
            }
        } else {
            list.add("我已从这家公司离职，退出");
            list.add("这不是我的企业，退出");
        }
        StringAdapter adapter = new StringAdapter(list);
        final MListDialog.Builder dialog = new MListDialog.Builder(context);
        dialog.setAdapter(adapter);
        dialog.create().show();
        dialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("点击", list.get(position));
                dialog.dissmiss();
                String str = "";
                String title = "";
                if (position == 0) {//我已从这家公司离职，退出
                    type = 1;
                    str = "离职退出后,您将无法进入企业，重新进入企业需要联系企业管理员。";
                    title = "是否从企业离职";
                }
                if (position == 1) {//这不是我的企业，退出
                    type = 2;
                    str = "退出后,您将无法进入企业，重新进入企业需要联系企业管理员。";
                    title = "是否退出企业";
                }
                createCustomDialog(str, title);
            }
        });
    }

    private void createCustomDialog(String content, String title) {
        ConfirmDialog.Builder confirmDialog = new ConfirmDialog.Builder(this);
        confirmDialog.setTitle(title);
        confirmDialog.setPositiveButtonColor(R.color.color4138);
        confirmDialog.setContent(content);
        confirmDialog.setOnNegativeListener(new ConfirmDialog.Builder.OnNegativeListener() {
            @Override
            public void onNegative(ConfirmDialog dialog) {
                dialog.dismiss();
            }
        });
        confirmDialog.setPositiveButton("退出", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                signOut();
            }
        });
        confirmDialog.show();
    }

    //登出企业或离职
    private void signOut() {
        if (TextUtils.isEmpty(comID)) {
            toast("公司ID不能为空！");
            return;
        }
        ExcitationPresenter.getInstance().userQuitCom(Globals.getToken(), type + "", comID, new DataResponseListener<String>() {
            @Override
            public void onSuccess(String dataResponse) {
                if (dataResponse.equals("success")) {
                    upToken("-1");
                }
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    /**
     * 登陆企业后更新token
     */
    private void upToken(String comId) {
        String token = Globals.getToken();
        HttpUser.getUpToken(token, comId, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            Log.e("跟新token", data);
            if (data != null) {
                try {
                    String msg = "";
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        finish();
                        String mtoken = jsonObject.optString("data");
                        msg = jsonObject.optString("msg");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            SharedPreferencesUtils.saveToken(mtoken, SignOutCompanyActivity.this);
                        }
                        toast("成功退出企业！");
                        finish();
                    } else {
                        toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("退出失败！" + new String(responseBody));
        }
    };

}
